<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Refund_model extends MY_Model {
	var $table = 'refund';
	
	public function __construct() {
		parent::__construct();
	}
	public function getRefundAll($config = array(), $like = array()) {		
		$config['field'] = 'r.id';
		$config['select'] = 'r.id,r.in_status,r.status,r.refund_num,r.refund_time,o.order_num,o.netpay,o.pay_method,o.contact_address,m.username as master';
		$config['join'] = array(
			array('order o', 'r.order_id=o.id', 'left'),
			array('manager m', 'r.op_user_id=m.id', 'left'),
			array('agent_assignment aa', 'o.address_id=aa.address_id', 'left'),
			array('agent a1', 'aa.agent_id=a1.id', 'left'),
			array('areas_enabled ae', 'o.address_id=ae.id', 'left'),
			array('areas a', 'ae.district_id=a.id', 'left')
		);
		$config['group_by'] = 'r.id';
		$config['totalCount'] = $this->get_search_num(NULL, $like, $config, ' r');
		if($config['offset'] >= $config['totalCount']) {
			$config['offset'] = 0;
			$config['pageNum'] = 1;
 		}
		$config['data'] = $this->search(NULL, $config, $like, false, ' r');
		return $config;
	}
	public function refundPack() {
		$query = $this->db->select('o.order_num,o.created_at,ag.username,concat_ws(\' \',a.description,ae.address) as address', false)
				->from($this->table . ' r')
				->join('order o', 'r.order_id=o.id', 'left')
				->join('agent ag', 'r.agent_id=ag.id', 'left')
				->join('areas_enabled ae', 'o.address_id=ae.id', 'left')
				->join('areas a', 'ae.district_id=a.id', 'left')
				->where(array('o.status' => REST_Controller::PAY_STATUS_REFUNDING,
					'r.status' => REST_Controller::STATUS_ACTIVE))
				->group_by('o.id')
				->get();
		return $query->result_array();
	}
	public function multiRefund($ids) {
		if(empty($ids)) {
			return NULL;
		}
		$idsArr = explode(',', $ids);
		$this->db->where_in('r.id', $idsArr);
		$this->db->where_in('o.pay_method', array(REST_Controller::PAY_METHOD_ALIPY, REST_Controller::PAY_METHOD_WECHAT));
		$this->db->where(array('o.status'=>  REST_Controller::PAY_STATUS_REFUNDING, 'r.status'=>  REST_Controller::STATUS_ACTIVE));
		$this->db->where('o.pay_time IS NOT NULL and o.ext_order_num IS NOT NULL');
		$query = $this->db->select('r.id,o.id as oid,o.user_id,o.order_num,o.address_id,o.ext_order_num,format(o.netpay/100, 2) as netpay,o.pay_method', false)
				->from($this->table . ' r')
				->join('order o', 'r.order_id=o.id')
				->get();
		return $query->result_array();
	}
	public function refund($data, $data1) {
		$this->db->trans_start();
		$this->db->update($this->table, $data, array('id'=>$data['id']));
		$this->db->update('order', $data1, array('id'=>$data['id']));
		$this->db->trans_complete();
		return $this->db->trans_status();
	}
}